package org.tzw.template.logger;

import android.content.Context;
import android.os.Environment;


import org.tzw.template.utils.FileUtil;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;


public class LogThread extends Thread {

    private static LogThread instance = null;

    private WeakReference<Context> context;
    private final Queue<String> logs;
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    public static LogThread getInstance() {
        if (instance == null) {
            synchronized (LogThread.class) {
                if (instance == null) {
                    instance = new LogThread();
                }
            }
        }
        return instance;
    }

    private LogThread() {
        super();
        logs = new ConcurrentLinkedQueue<>();
        setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                throwable.printStackTrace();
            }
        });
        start();
    }

    public void write(Context context, String log) {
        this.context = new WeakReference<>(context);
        synchronized (LogThread.this) {
            if (logs.size() > 50) {
                // 累积日志超过50条，合并成1条日志一次性输出
                StringBuilder sb = new StringBuilder("");
                do {
                    String temp = logs.poll();
                    if (temp == null) {
                        break;
                    } else {
                        sb.append(temp);
                    }
                } while (true);
                logs.offer(sb.toString());
            }
            logs.offer(log);
            instance.notify();
        }
    }

    @Override
    public void run() {
        while (true) {
            String log = logs.poll();
            synchronized (LogThread.this) {
                if (log == null) {
                    try {
                        instance.wait();
                        log = logs.poll();
                        doWrite(log);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break;
                    }
                } else {
                    doWrite(log);
                }
            }
        }
    }

    private void doWrite(String log) {
        PrintWriter pw = null;
        try {
            if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
                File logDir = FileUtil.getLogDir(context.get());
                File logFile = new File(logDir, sdf.format(new Date()));
                if (!logFile.exists()) {
                    logFile.createNewFile();
                }
                pw = new PrintWriter(new BufferedWriter(new FileWriter(logFile, true)));
                pw.print(log);
                pw.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (pw != null) {
                    pw.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
